package com.tekj.cxqcb.view.Module.activity.StoreModule;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tekj.cxqcb.MainBActivity;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.ApiShopServiceTypeBean;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.view.Module.adapter.ClassificationAdapter;
import com.tekj.cxqcb.view.Module.decoration.SpacesItemDecoration;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;

import butterknife.BindView;
import butterknife.OnClick;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.tool.Tools;
import es.dmoral.toasty.Toasty;

import static android.widget.ListPopupWindow.MATCH_PARENT;

/**
 * 分类管理
 */
public class ClassificationTwoActivity extends BaseActivity {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.srv_main)
    SwipeRecyclerView srvMain;

    BusinessDao businessDao;
    ClassificationAdapter classificationAdapter;
    boolean isSort = false;
    ApiShopServiceTypeBean.DataBean parentId;
    int type;

    @Override
    public void init() {
        type = getIntent().getIntExtra("type", 0);
        tvTitle.setText(type == 0 ? "服务商品分类管理" : "分类选择");
        businessDao = new BusinessDao(activity, this);
        parentId = (ApiShopServiceTypeBean.DataBean) getIntent().getSerializableExtra("parentId");

        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
                SwipeMenuItem deleteItem1 = new SwipeMenuItem(activity)
                        .setHeight(MATCH_PARENT)
                        .setWidth(Tools.dip2Px(activity, 60))
                        .setBackgroundColor(getResources().getColor(R.color.colorPrimary))
                        .setText("编辑").setTextSize(13)
                        .setTextColor(getResources().getColor(R.color.white));
                rightMenu.addMenuItem(deleteItem1);

                SwipeMenuItem deleteItem2 = new SwipeMenuItem(activity)
                        .setHeight(MATCH_PARENT)
                        .setWidth(Tools.dip2Px(activity, 60))
                        .setBackgroundColor(getResources().getColor(R.color.red))
                        .setText("删除").setTextSize(13)
                        .setTextColor(getResources().getColor(R.color.white));

                rightMenu.addMenuItem(deleteItem2);
                // 注意：哪边不想要菜单，那么不要添加即可。
            }
        };

        srvMain.setSwipeMenuCreator(mSwipeMenuCreator);

        // 设置监听器。
        // 菜单点击监听。
        OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, final int position) {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();

                // 左侧还是右侧菜单：
                int direction = menuBridge.getDirection();
                if (direction == -1) {
                    // 菜单在Item中的Position：
                    switch (menuBridge.getPosition()) {
                        case 0:
                            showPop(classificationAdapter.getData().get(position).getTypeName(),
                                    classificationAdapter.getData().get(position).getTypeBrief(),
                                    classificationAdapter.getData().get(position).getId());
                            break;
                        case 1:
                            Tools.showNormalDialogOne(activity, "删除", "是否将该分类删除"
                                    , new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            businessDao.DelLevel(MainBActivity.User.getShopId(),
                                                    classificationAdapter.getData().get(position).getId());
                                        }
                                    }, null);
                            break;
                    }

                }
            }
        };
        srvMain.setOnItemMenuClickListener(mItemMenuClickListener);
        classificationAdapter = new ClassificationAdapter(null);
        classificationAdapter.setArrow(false);
        srvMain.setLayoutManager(new LinearLayoutManager(activity));
        srvMain.setAdapter(classificationAdapter);
        srvMain.addItemDecoration(new SpacesItemDecoration(2));

        srvMain.setOnItemMoveListener(new OnItemMoveListener() {
            @Override
            public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                //移动后回调
                return false;
            }

            @Override
            public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
                //删除回调
            }
        });
        classificationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (type == 1) {
                    Intent intent = new Intent();
                    intent.putExtra("level1",  parentId);
                    intent.putExtra("level2", classificationAdapter.getData().get(position));
                    setResult( RESULT_OK,intent);
                    finish();
                }
            }
        });
        businessDao.ApiShopServiceType(MainBActivity.User.getShopId(), parentId.getId());
    }

    @Override
    public int setLayout() {
        return R.layout.activity_classification;
    }

    @Override
    public void initLoadStart() {

    }

    @Override
    public void initLoadEnd() {

    }

    @Override
    public void initBindingView(Object mBean) {

        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 查询所有分类:
                ApiShopServiceTypeBean typeBean = (ApiShopServiceTypeBean) bindingViewBean.getBean();
                if (typeBean.getCode().equals("0000000")) {
                    classificationAdapter.setNewData(typeBean.getData());
                }
                break;
            case 新增二级分类:
                SuccessfulRevision(bindingViewBean);
                break;

            case 编辑分类管理:
                SuccessfulRevision(bindingViewBean);
                break;
            case 删除分类管理:
                SuccessfulRevision(bindingViewBean);
                break;
        }

    }

    void SuccessfulRevision(BindingViewBean bindingViewBean) {
        PubStatusBean pubStatusBean2 = (PubStatusBean) bindingViewBean.getBean();
        if (pubStatusBean2.getCode().equals("0000000")) {
            popupWindow.dismiss();
            businessDao.ApiShopServiceType(MainBActivity.User.getShopId(), parentId.getId());
        }
        Toasty.normal(activity, pubStatusBean2.getMsg()).show();
    }

    @OnClick({R.id.ll_back, R.id.ll_right, R.id.tv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.ll_right:
                isSort = !isSort;
                tvR.setText(isSort ? "确定" : "排序");
                srvMain.setLongPressDragEnabled(isSort);
                Toasty.normal(activity, isSort ? "长按拖动进行排序" : "排序关闭").show();
                break;
            case R.id.tv_add:
                showPop();
                break;
        }
    }

    private PopupWindow popupWindow;
    private View popupView;
    private TranslateAnimation animation;

    void initPop() {
        Tools.lightoff(activity);
        popupView = View.inflate(activity, R.layout.pop_add_classification, null);
        popupWindow = new PopupWindow(popupView, width - Tools.dip2Px(activity, 40),
                LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 0);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setDuration(200);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Tools.lighton(activity);
            }
        });
    }

    private void showPop() {
        initPop();
        TextView tvQx = popupView.findViewById(R.id.tv_qx);
        TextView tvQr = popupView.findViewById(R.id.tv_qr);
        final EditText etClassName = popupView.findViewById(R.id.et_class_name);
        final EditText etClassContent = popupView.findViewById(R.id.et_class_content);
        etClassContent.setVisibility(View.VISIBLE);

        tvQx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvQr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etClassName.getText().toString().trim().equals("")) {
                    Toasty.normal(activity, "请先填写分类名称").show();
                    return;
                }
                if (etClassContent.getText().toString().trim().equals("")) {
                    Toasty.normal(activity, "请先填写分类简介").show();
                    return;
                }
                businessDao.AddTwoLevel(MainBActivity.User.getShopId(), parentId.getId(),
                        etClassName.getText().toString().trim(), etClassContent.getText().toString());
            }
        });

        popupWindow.showAtLocation(rlTitleBg, Gravity.CENTER, 0, 0);
        popupView.startAnimation(animation);
    }

    /**
     * 编辑
     *
     * @param name
     * @param content
     * @param id
     */
    private void showPop(String name, String content, final String id) {
        initPop();
        TextView tvTitle = popupView.findViewById(R.id.tv_title);
        tvTitle.setText("编辑");
        TextView tvQx = popupView.findViewById(R.id.tv_qx);
        TextView tvQr = popupView.findViewById(R.id.tv_qr);
        final EditText etClassName = popupView.findViewById(R.id.et_class_name);
        final EditText etClassContent = popupView.findViewById(R.id.et_class_content);
        etClassContent.setVisibility(View.VISIBLE);

        etClassName.setText(name);
        etClassContent.setText(content);

        tvQx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvQr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etClassName.getText().toString().trim().equals("")) {
                    Toasty.normal(activity, "请先填写分类名称").show();
                    return;
                }
                if (etClassContent.getText().toString().trim().equals("")) {
                    Toasty.normal(activity, "请先填写分类简介").show();
                    return;
                }
                businessDao.EditLevel(id, etClassName.getText().toString().trim(), etClassContent.getText().toString());
            }
        });

        popupWindow.showAtLocation(rlTitleBg, Gravity.CENTER, 0, 0);
        popupView.startAnimation(animation);
    }
}
